package com.hp.attendance.serlvet;

import com.hp.attendance.util.Code;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

@WebServlet("/code")
public class CodeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //验证码
        getImage(req,resp);
    }


    public void getImage(HttpServletRequest request,HttpServletResponse resp) throws IOException {
        //1.创建一张图片
        BufferedImage image = new BufferedImage(100,50,BufferedImage.TYPE_INT_RGB);
        //2.创建一只画笔
        Graphics graphics = image.getGraphics();
        //3.给图片填充背景色
        graphics.setColor(Code.ranDomColor());
        //4.把背景色填充的范围
        graphics.fillRect(0,0,100,50);
        //5.画干扰线
        Code.randomLine(graphics);
        //6.画随机验证码
        String code = Code.getText(graphics);
        request.getSession().setAttribute("code",code);
        //7.写入到页面
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
